package com.scuec.trainingmanagementsys.service.impl;

import com.scuec.trainingmanagementsys.entity.Administrator;
import com.scuec.trainingmanagementsys.mapper.AdministratorMapper;
import com.scuec.trainingmanagementsys.service.AdministratorService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdministratorServiceImpl implements AdministratorService {

    @Resource
    private AdministratorMapper administratorMapper;

    // 整表查询
    @Override
    public List<Administrator> listAll() {
        return administratorMapper.selectAll();
    }

    // 姓名模糊查询（自动补全百分号）
    @Override
    public List<Administrator> listByName(String name) {
        if (!StringUtils.hasText(name)) {
            return listAll(); // 若参数为空，返回全部数据（可根据需求调整）
        }
        return administratorMapper.selectByName(name);
    }

    // 删除单条记录
    @Override
    public boolean deleteById(Integer id) {
        return id != null && administratorMapper.deleteById(id) > 0;
    }

    // 批量删除（过滤空ID）
    @Override
    public boolean deleteBatch(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        // 过滤无效ID
        List<Integer> validIds = ids.stream()
                .filter(id -> id != null)
                .collect(Collectors.toList());
        return !validIds.isEmpty() && administratorMapper.deleteBatch(validIds) > 0;
    }

    // 插入记录（主键自增无需处理ID）
    @Override
    public boolean save(Administrator admin) {
        return admin != null && administratorMapper.insert(admin) > 0;
    }

    // 修改记录（需确保ID存在）
    @Override
    public boolean update(Administrator admin) {
        return admin != null && admin.getAdministratorID() != null &&
                administratorMapper.update(admin) > 0;
    }

    @Override
    public Administrator login(String username, String password, String type) {
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password) || !StringUtils.hasText(type)) {
            return null;
        }
        return administratorMapper.selectByUsernamePasswordAndType(username, password, type);
    }

    @Override
    public int getAdministratorCount() {
        return administratorMapper.getAdministratorCount();
    }

    // 根据管理员账号查询管理员信息
    @Override
    public Administrator getAdministratorByUsername(String administratorName) {
        if (!StringUtils.hasText(administratorName)) {
            return null;
        }
        return administratorMapper.selectByAdministratorName(administratorName);
    }

    // 根据管理员账号更新
    @Override
    public boolean updateByAdministratorName(Administrator admin) {
        return admin != null && !StringUtils.isEmpty(admin.getAdministratorName()) &&
                administratorMapper.updateByAdministratorName(admin) > 0;
    }
}